codeforces 20C Dijkstra?

Description

You are given a weighted undirected graph. The vertices are enumerated from 1 to n. Your task is to find the shortest path between the vertex 1 and the vertex n.

Input

The first line contains two integers n and m (2 ≤ n ≤ 105, 0 ≤ m ≤ 105), where n is the number of vertices and m is the number of edges. Following m lines contain one edge each in form ai, bi and wi (1 ≤ ai, bi ≤ n, 1 ≤ wi ≤ 106), where ai, bi are edge endpoints and wi is the length of the edge.

It is possible that the graph has loops and multiple edges between pair of vertices.

Output

Write the only integer -1 in case of no path. Write the shortest path in opposite case. If there are many solutions, print any of them.

Sample Input

Input
5 6
1 2 2
2 5 5
2 3 4
1 4 1
4 3 3
3 5 1
Output
1 4 3 5 
Input
5 6
1 2 2
2 5 5
2 3 4
1 4 1
4 3 3
3 5 1
Output
1 4 3 5 
题意:给出一张n个点m条边的无向图 (2 ≤ n ≤ 105, 0 ≤ m ≤ 105),输出从1到n的任意一条最短路径。
解法:dijkstra或者spfa,用pre数组记录到达每个点最短距离的前驱结点。
注意:
        路径的长度范围是 1 ≤ wi ≤ 106,从1到n的最短路径长度可能超出int范围。
        没有路径从1到达n时要输出-1。
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
typedef long long LL;
typedef pair<LL,int> pii;
const int maxn = 100010;
const int maxm = 200010;
int v[maxm],next[maxm],w[maxm];
int first[maxn],pre[maxn],res[maxn],e;
LL d[maxn];

void init(){
    e = 0;
    memset(first,-1,sizeof(first));
}

void add_edge(int a,int b,int c){
    v[e] = b;next[e] = first[a];w[e] = c;first[a] = e++;
}

void dijkstra(int src){
    priority_queue <pii,vector<pii>,greater<pii> > q;
    memset(d,-1,sizeof(d));
    d[src] = 0;
    q.push(make_pair(0,src));
    while(!q.empty()){
        while(!q.empty() && q.top().first > d[q.top().second])  q.pop();
        if(q.empty())   break;
        int u = q.top().second;
        q.pop();
        for(int i = first[u];i != -1;i = next[i]){
            if(d[v[i]] > d[u]+w[i] || d[v[i]] == -1){
                d[v[i]] = d[u]+w[i];
                q.push(make_pair(d[v[i]],v[i]));
                pre[v[i]] = u;
            }
        }
    }
}

int main(){
    init();
    int n,m,a,b,c;
    scanf("%d%d",&n,&m);
    for(int i = 0;i < m;i++){
        scanf("%d%d%d",&a,&b,&c);
        add_edge(a,b,c);
        add_edge(b,a,c);
    }
    dijkstra(1);
    int now = n,cnt = 0;
    if(d[n] == -1){
        printf("-1");
        return 0;
    }
    while(now != 1){
        res[cnt++] = now;
        now = pre[now];
    }
    res[cnt++] = 1;
    for(int i = cnt-1;i >= 0;i--)  printf("%d ",res[i]);
    return 0;
}

这题不错,正好最近在看最短路的东西,就拿它练手了~
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值